﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Belmost4PDA.Fasade;

namespace Belmost4PDA.Logic
{
    public class brDef
    {
        // data
        private DefectsReader.brDefItem brDefItem = null;
        public DefectsReader.DefItem DefItem = null;
        public defControlStrategy controls = null;
        private static List<DefectsReader.DefItem> DefItems = null;
        public static event DataChaged OnDataChange;
        public delegate void DataChaged(defControlStrategy args);

        public brElement parentElement = null;
        public static void Changed(defControlStrategy strategyInvoker)
        {
            if(OnDataChange!=null)
                OnDataChange(strategyInvoker);  
        }
        private brDef(DefectsReader.brDefItem _brDefItem)
        {
            InitInstance(_brDefItem);
        }

        private void InitInstance(DefectsReader.brDefItem _brDefItem)
        {
            // сохранить ссылку на brDefItem
            brDefItem = _brDefItem;
            // найти ссылку на DefItem (по defCode)
            foreach (DefectsReader.DefItem defItem in DefItems)
            {
                if (defItem.defCode == _brDefItem.defCode)
                    DefItem = defItem;
            }
            // создание контролов
            controls = defControlStrategy.GetStraregy(brDefItem, DefItem, this);
            OnDataChange += controls.OnChange;
        }

        private brDef(DefectsReader.brDefItem item, brElement _parent)
        {
            InitInstance(item);
            parentElement = _parent;
        }

        public static List<brDef> GetDefForElem(ElementItem item, brElement ownerElement)
        {
            if (DefItems == null)
                DefItems = DefectsReader.GetDefItems();
            // read def items for bridge
            List<DefectsReader.brDefItem> items = DefectsReader.GetBrDefItems(item.ID, GlobalStates.IDBR);
            List<brDef> retItems = new List<brDef>();
            foreach (DefectsReader.brDefItem brDefItem in items)
            {
                retItems.Add(new brDef(brDefItem, ownerElement));
            }
            return retItems;
        }

        public void CreateDefControls(Form _form)
        {
            controls.AddToForm(_form);
        }

        public void Post()
        {
            controls.Post(brDefItem);
        }

        public void CheckOff()
        {
            controls.CheckOff();
        }
    }

}
